const { Op } = require('sequelize');
const Novel = require('../models/Novel');
const Author = require('../models/Author');

exports.getNovels = async (ctx) => {
  const { page = 1, size = 10, q, category, status } = ctx.query;
  const offset = (page - 1) * size;

  try {
    const where = {};
    if (q) where.novel_name = { [Op.like]: `%${q}%` };
    if (category) where.category = category;
    if (status) where.status = status;

    const { count, rows } = await Novel.findAndCountAll({
      where,
      include: [{
        model: Author,
        attributes: ['name']
      }],
      limit: parseInt(size),
      offset: parseInt(offset)
    });

    ctx.body = {
      content: rows,
      totalElements: count
    };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.getNovelById = async (ctx) => {
  try {
    const novel = await Novel.findByPk(ctx.params.id);
    if (novel) {
      ctx.body = novel;
    } else {
      ctx.status = 404;
      ctx.body = { error: 'Novel not found' };
    }
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.createNovel = async (ctx) => {
  try {
    const novel = await Novel.create(ctx.request.body);
    ctx.status = 201;
    ctx.body = novel;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.updateNovel = async (ctx) => {
  const { id } = ctx.params;
  try {
    const novel = await Novel.findByPk(id);
    if (!novel) {
      ctx.status = 404;
      ctx.body = { error: 'Novel not found' };
      return;
    }
    await novel.update(ctx.request.body);
    ctx.body = novel;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.updateNovelStatus = async (ctx) => {
  const { id } = ctx.params;
  const { status } = ctx.request.body;
  try {
    const novel = await Novel.findByPk(id);
    if (!novel) {
      ctx.status = 404;
      ctx.body = { error: 'Novel not found' };
      return;
    }
    await novel.update({ status });
    ctx.body = { message: 'Status updated successfully' };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.deleteNovel = async (ctx) => {
  const { id } = ctx.params;
  try {
    const result = await Novel.destroy({ where: { novel_id: id } });
    if (result === 0) {
      ctx.status = 404;
      ctx.body = { error: 'Novel not found' };
      return;
    }
    ctx.status = 204; // No Content
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};